<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Menu extends Controller
{
    public function action_index()
    {
        $max_level = Request::$current->param('level', '-1');
        $menu = View::factory('menu')->set('chapters', $this->get_chapters($max_level));
        
        Request::$current->response()->body($menu->render());        
    }
    
    public function get_chapters($max_level = -1, $parent_id = 0, $cur_level = 1)
    {
        $chapters = array();

        $result = DB::query(Database::SELECT, "SELECT c1.id as `id`, c1.name as `name`, c1.href as `href`, 
                                                        c1.hide as `hide`, c1.parent_id as `parent_id`, 
                                                        (COUNT(c2.name)>0) as `subchapters` 
                                                 FROM  `chapters` AS  `c1` 
                                                 LEFT JOIN  `chapters` AS  `c2` ON c2.parent_id = c1.id
                                                 WHERE (c1.parent_id =:parent_id AND c1.hide='show') 
                                                 GROUP BY c1.href
                                                 ORDER BY c1.pos")
                    ->param(':parent_id', $parent_id)
                    ->execute()
                    ->as_array(); 
        
        foreach ($result as $chapter) {
            if($chapter['subchapters'] && ($cur_level < $max_level || $max_level == -1))
                $chapter['subchapters'] = $this->get_chapters($max_level, $chapter['id'], $cur_level + 1);
            else
                unset($chapter['subchapters']);
            $chapters[] = $chapter;
        }
        return $chapters;
    }
}